import { login } from '@/service/user';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { message } from 'antd';
import { createStyles } from 'antd-style';
import React from 'react';
import { flushSync } from 'react-dom';

const useStyles = createStyles(() => {
  return {
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});

const Login: React.FC = () => {
  const { styles } = useStyles();
  const { initialState, setInitialState } = useModel('@@initialState');

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    console.log('@@@ userInfo', userInfo)
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  // 登录提交
  const loginSubmit = async (values) => {
    const { account, password } = values;
    const res = await login({ account, password });
    console.log('@@@ res', res);
    if (res) {
      localStorage.setItem('cms-project-token', res.token);
      message.success('登录成功！');
      await fetchUserInfo();
      history.push('/');
      return
    }
  };

  return (
    <div className={styles.container}>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
          paddingTop: 200,
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          title="内部管理平台"
          subTitle=" "
          initialValues={{
            autoLogin: true,
          }}
          onFinish={loginSubmit}
        >
          <ProFormText
            name="account"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined />,
            }}
            placeholder="账号（邮箱格式）"
            rules={[
              {
                required: true,
                message: '请输入账号',
              },
              {
                type: 'email',
                message: '请输入邮箱格式',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined />,
            }}
            placeholder="8-16位数字+字母的密码"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
              {
                pattern: /^(?=.*[a-zA-Z])(?=.*\d).{8,16}$/,
                message: '请输入8-16位数字+字母的密码',
              },
            ]}
          />
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
